package com.leisurexi.gedis.client.util;

import io.netty.channel.Channel;
import org.springframework.util.StringUtils;

import java.net.SocketAddress;

/**
 * Some utilities for remoting.
 *
 * @author: leisurexi
 * @date: 2020-09-08 14:55
 */
public class RemotingUtils {

    private RemotingUtils() {
    }

    private static final String EMPTY = "";

    /**
     * 获取客户端 {@link Channel} 的地址
     */
    public static String parseRemoteAddress(final Channel channel) {
        if (null == channel) {
            return EMPTY;
        }
        final SocketAddress remote = channel.remoteAddress();
        return doParse(remote != null ? remote.toString().trim() : EMPTY);
    }

    public static String parseSocketAddressToString(SocketAddress socketAddress) {
        if (socketAddress != null) {
            return doParse(socketAddress.toString().trim());
        }
        return EMPTY;
    }

    public static String parseLocalAddress(final Channel channel) {
        if (null == channel) {
            return EMPTY;
        }
        final SocketAddress local = channel.localAddress();
        return doParse(local != null ? local.toString().trim() : EMPTY);
    }

    private static String doParse(String addr) {
        if (StringUtils.isEmpty(addr)) {
            return EMPTY;
        }
        if (addr.charAt(0) == '/') {
            return addr.substring(1);
        } else {
            int len = addr.length();
            for (int i = 1; i < len; ++i) {
                if (addr.charAt(i) == '/') {
                    return addr.substring(i + 1);
                }
            }
            return addr;
        }
    }

}
